package org.dbstar.scheduler.control.db.authority;

import java.sql.Types;
import java.util.HashSet;
import java.util.Set;

import org.dbstar.scheduler.beans.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;


/**
 * 批量插入认证用户的授权信息
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-6-5
 */
public class AuthorityInsert extends SimpleJdbcInsert {
	public AuthorityInsert(JdbcTemplate jdbcTemplate) {
		super(jdbcTemplate);
		withTableName("SCHD_AUTHORITY");
		usingColumns("USERNAME", "DISPLAY_NAME", "AUTHORITY");
	}

	public int insert(User user) {
		Set<SqlParameterSource> set = new HashSet<SqlParameterSource>();
		for (String authority : user.getAuthorities()) {
			if (authority.startsWith("GROUP_")) {
				MapSqlParameterSource source = new MapSqlParameterSource();
				source.addValue("USERNAME", user.getUsername(), Types.VARCHAR);
				source.addValue("DISPLAY_NAME", user.getDisplayName(), Types.VARCHAR);
				source.addValue("AUTHORITY", authority, Types.VARCHAR);
				set.add(source);
			}
		}
		int r[] = super.executeBatch(set.toArray(new SqlParameterSource[set.size()]));
		int count = 0;
		for (int i : r) {
			count += i;
		}
		return count;
	}
}
